<?php
/**
 * Created by PhpStorm.
 * User: liangjianbiao
 * Date: 2019/1/22
 * Time: 17:47
 */

namespace App\Handlers;
use Image;

class ImageUploadHandler
{
    protected $allowed_ext = ['png', 'jpg', 'gif', 'jpeg'];

    public function save($file, $folder, $file_prefix, $max_width = false)
    {
        $folder_name = "uploads/images/{$folder}/". date("Ym", time()) . '/' . date("d" , time()) . '/';
        $upload_path = public_path() . '/' . $folder_name;
        $extension = strtolower($file->getClientOriginalExtension())?:'png';
        $file_name = $file_prefix . '_' . time() . '_' . str_random(10) . '.' . $extension;
        if(!in_array($extension, $this->allowed_ext)){
            return false;
        }
        $file->move($upload_path, $file_name);
        if($max_width && $extension != 'gif'){
            $this->reduceSize($upload_path.'/'.$file_name, $max_width);
        }
        return [
            'path' => config('app.url') . "/$folder_name/$file_name"
        ];
    }

    public function reduceSize($file_path, $max_width)
    {
        $img = Image::make($file_path);
        $img->resize($max_width, null, function ($constranint){
            $constranint->aspectRatio();
            $constranint->upsize();
        });
        $img->save();
    }
}